<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="秒杀名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入秒杀名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in statusDict" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
          v-hasPermi="['eb:store-seckill-manger:create']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="秒杀名称" align="center" prop="name" />
      <el-table-column label="秒杀时段" align="center" width="180">
        <template v-slot="scope">
          <!-- 显式传递数值，避免转为空字符串 -->
          <span>{{ formatTimeRange(scope.row.startTime || 0, scope.row.endTime || 0) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" width="180">
        <template v-slot="scope">
          <div class="image-container">
            <!-- 显示所有图片 -->
            <div v-if="getImageList(scope.row.silderImgs).length > 0" class="image-gallery">
              <el-image 
                v-for="(img, index) in getImageList(scope.row.silderImgs)"
                :key="index"
                :src="img"
                alt="轮播图" 
                class="table-image"
                :preview-src-list="getImageList(scope.row.silderImgs)"
                fit="cover"
                @error="handleImageError"
                @load="handleImageLoad">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </div>
            <div v-else class="no-image">无图片</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template v-slot="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" active-color="#13ce66"
            inactive-color="#ff4949" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
            v-hasPermi="['eb:store-seckill-manger:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['eb:store-seckill-manger:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 对话框(添加 / 修改) -->
    <StoreSeckillMangerForm ref="formRef" @success="getList" />
  </div>
</template>

<script>
import * as StoreSeckillMangerApi from '@/api/marketing/storeseckillmanger';
import StoreSeckillMangerForm from './StoreSeckillMangerForm.vue';
export default {
  name: "StoreSeckillManger",
  components: {
    StoreSeckillMangerForm,
  },
  data() {
    return {
      statusDict: [
        { value: '1', label: '开启' },
        { value: '0', label: '关闭' }
      ],
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 秒杀商品列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: null,
        status: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 处理状态变更
    async handleStatusChange(row) {
      console.log(row);
      try {
        // 显示加载状态（可选）
        row.loading = true;

        // 调用 API 更新状态
        const res = await StoreSeckillMangerApi.updateStatus({
          id: row.id,
          status: row.status
        });

        // 更新成功提示
        this.$message.success(res.message || '状态更新成功');
      } catch (error) {
        // 失败时回滚状态
        row.status = row.status === 1 ? 0 : 1;
        this.$message.error(error.message || '状态更新失败');
      } finally {
        // 隐藏加载状态
        row.loading = false;
      }
    },
    // 格式化时间段（例如：0 → 00:00，8 → 08:00）
    formatTimeRange(start, end) {
      if (start === null || end === null) return '-'; // 处理未选择的情况
      return `${this.formatHour(start)} - ${this.formatHour(end)}`;
    },

    // 格式化单小时（补零处理，确保0显示为00:00）
    formatHour(hour) {
      const hourStr = (typeof hour === 'number' ? hour : 0).toString(); // 确保为数字或0
      return hourStr.padStart(2, '0') + ':00';
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await StoreSeckillMangerApi.getStoreSeckillMangerPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除秒杀商品编号为"' + id + '"的数据项?')
      try {
        await StoreSeckillMangerApi.deleteStoreSeckillManger(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch { }
    },
    // 获取第一张图片
    getFirstImage(silderImgs) {
      if (!silderImgs) return null;
      
      try {
        // 如果是字符串，尝试解析为JSON
        let imageArray = silderImgs;
        if (typeof silderImgs === 'string') {
          imageArray = JSON.parse(silderImgs);
        }
        
        // 确保是数组且有数据
        if (Array.isArray(imageArray) && imageArray.length > 0) {
          const firstImg = imageArray[0];
          // 如果是对象且有sattDir字段
          if (typeof firstImg === 'object' && firstImg.sattDir) {
            return firstImg.sattDir;
          }
          // 如果是字符串（直接是URL）
          if (typeof firstImg === 'string') {
            return firstImg;
          }
        }
      } catch (error) {
        console.error('解析轮播图数据失败:', error);
      }
      
      return null;
    },
    // 处理图片加载错误
    handleImageError(event) {
      event.target.src = '/path/to/default/image.jpg'; // 替换为实际的默认图片路径
    },
    // 处理图片加载成功
    handleImageLoad(event) {
      // 可以在这里添加处理逻辑，例如记录加载成功的图片
    },
    // 获取图片列表
    getImageList(silderImgs) {
      if (!silderImgs) return [];
      
      try {
        // 如果是字符串，尝试解析为JSON
        let imageArray = silderImgs;
        if (typeof silderImgs === 'string') {
          try {
            imageArray = JSON.parse(silderImgs);
          } catch (parseError) {
            // 如果解析失败，可能是直接的URL字符串
            return [silderImgs];
          }
        }
        
        // 确保是数组且有数据
        if (Array.isArray(imageArray) && imageArray.length > 0) {
          return imageArray
            .map(img => {
              // 如果是对象且有sattDir字段
              if (typeof img === 'object' && img.sattDir) {
                return img.sattDir;
              }
              // 如果是字符串（直接是URL）
              if (typeof img === 'string') {
                return img;
              }
              return null;
            })
            .filter(url => url !== null && url !== undefined && url.trim() !== '');
        }
      } catch (error) {
        console.error('解析轮播图数据失败:', error);
      }
      
      return [];
    },
  }
};
</script>

<style scoped>
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

.image-gallery {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  gap: 5px;
  padding: 5px 0;
  max-width: 160px;
}

.table-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  cursor: pointer;
  flex-shrink: 0;
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>
